<template>
  <div class="app-container">

    <div class="table-layout">
      <el-row>
        <el-col :span="3" class="table-cell-title">活动标题</el-col>
        <el-col :span="3" class="table-cell-title">活动类型</el-col>
        <el-col :span="3" class="table-cell-title">开始时间</el-col>
        <el-col :span="3" class="table-cell-title">结束时间</el-col>
        <el-col :span="3" class="table-cell-title">活动状态</el-col>
        <el-col :span="3" class="table-cell-title">活动创建人</el-col>
      </el-row>
      <el-row>
        <el-col :span="3" class="table-cell">{{ activity.title }}</el-col>
        <el-col :span="3" class="table-cell">{{ activity.type | formatType }}</el-col>
        <el-col :span="3" class="table-cell">{{ activity.startTime }}</el-col>
        <el-col :span="3" class="table-cell">{{ activity.endTime }}</el-col>
        <el-col :span="3" class="table-cell">{{ activity.state | formatState }}</el-col>
        <el-col :span="3" class="table-cell">{{ activity.addBy }}</el-col>
      </el-row>
    </div>

    <div class="table-layout">
      <el-row>
        <el-col :span="3" class="table-cell-title">浏览数</el-col>
        <el-col :span="3" class="table-cell-title">分享数</el-col>
        <el-col :span="3" class="table-cell-title">报名数</el-col>
        <el-col :span="3" class="table-cell-title">成团数</el-col>
      </el-row>
      <el-row>
        <el-col :span="3" class="table-cell">{{ activity.views }}</el-col>
        <el-col :span="3" class="table-cell">{{ activity.shares }}</el-col>
        <el-col :span="3" class="table-cell">{{ activity.applications }}</el-col>
        <el-col :span="3" class="table-cell">{{ activity.groupons }}</el-col>
      </el-row>
    </div>

    <div class="table-layout">
      <el-row>
        <el-col :span="3" class="table-cell-title">科目</el-col>
        <el-col :span="3" class="table-cell-title">原价</el-col>
        <el-col :span="3" class="table-cell-title">团购价</el-col>
        <el-col :span="3" class="table-cell-title">成团要求人数</el-col>
      </el-row>
      <el-row v-for="(item, index) in activity.rulesList" :key="index" :value="item">
        <el-col :span="3" class="table-cell">{{ item.subject }}</el-col>
        <el-col :span="3" class="table-cell">{{ item.origin }}</el-col>
        <el-col :span="3" class="table-cell">{{ item.onsale }}</el-col>
        <el-col :span="3" class="table-cell">{{ item.limited }}</el-col>
      </el-row>
    </div>

    <div class="table-layout">
      <ve-histogram :extend="chartExtend" :data="grouponDatas" :settings="chartSettings" />
    </div>

    <div class="table-layout">
      <ve-histogram :extend="chartExtend" :data="statisticsDatas" :settings="statisticsSettings" />
    </div>

    <div class="table-layout">
      <ve-line :extend="chartExtend" :data="orderDatas" :settings="orderSettings" />
    </div>

    <!-- 查询操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.grouponCode" clearable class="filter-item" style="width: 200px;" placeholder="请输入团号" />
      <el-input v-model="listQuery.subject" clearable class="filter-item" style="width: 200px;" placeholder="请输入科目" />
      <el-input v-model="listQuery.userName" clearable class="filter-item" style="width: 200px;" placeholder="请输入用户昵称" />
      <el-select v-model="listQuery.state" clearable style="width: 200px" class="filter-item" placeholder="请选择团状态">
        <el-option v-for="type in stateOptions" :key="type.value" :label="type.label" :value="type.value" />
      </el-select>
      <el-select v-model="listQuery.payState" clearable style="width: 200px" class="filter-item" placeholder="请选择支付状态">
        <el-option v-for="type in payStateOptions" :key="type.value" :label="type.label" :value="type.value" />
      </el-select>
      <el-select v-model="listQuery.userType" clearable style="width: 200px" class="filter-item" placeholder="请选择用户类型">
        <el-option v-for="type in userTypeOptions" :key="type.value" :label="type.label" :value="type.value" />
      </el-select>
      <el-button v-permission="['GET /admin/activity/activityGroupon/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column type="expand">
        <template slot-scope="props">
          <div v-for="item in props.row.subVoList" :key="item.id" class="groupon-list">
            <div class="groupon-cell">
              <img :src="item.image" width="40">
            </div>
            <div class="groupon-cell">
              {{ item.grouponId | formatGrouponId }}
            </div>
            <div class="groupon-cell">
              微信名：{{ item.userName }}
            </div>
            <div class="groupon-cell">
              学员姓名：{{ item.contactName }}
            </div>
            <div class="groupon-cell">
              学员年龄：{{ item.userAge }}
            </div>
            <div class="groupon-cell">
              联系电话：{{ item.contactPhone }}
            </div>
            <div class="groupon-cell">
              学员类型：{{ item.userType | formatUserType }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="团编号" prop="grouponCode" />
      <el-table-column align="center" label="团人数/满人" prop="grouponSize" />
      <el-table-column align="center" label="微信头像" prop="image">
        <template slot-scope="scope">
          <div class="picture">
            <img :src="scope.row.image" width="40">
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="微信名" prop="userName" />
      <el-table-column align="center" label="学员姓名" prop="contactName" />
      <el-table-column align="center" label="学员年龄" prop="userAge" />
      <el-table-column align="center" label="联系电话" prop="contactPhone" />
      <el-table-column align="center" label="科目" prop="subject" />
      <el-table-column align="center" label="学员类型" prop="userType">
        <template slot-scope="scope">{{ scope.row.userType | formatUserType }}</template>
      </el-table-column>
      <el-table-column align="center" label="是否团长" prop="grouponId">
        <template slot-scope="scope">{{ scope.row.grouponId | formatGrouponId }}</template>
      </el-table-column>
      <el-table-column align="center" label="开团/参团状态" prop="state">
        <template slot-scope="scope">{{ scope.row.state | formatGrouponState }}</template>
      </el-table-column>
      <el-table-column align="center" label="订单号" prop="orderCode" />
      <el-table-column align="center" label="微信支付单号" prop="payId" />
      <el-table-column align="center" label="支付金额(元)" prop="orderPrice" />
      <el-table-column align="center" label="支付状态" prop="payState">
        <template slot-scope="scope">{{ scope.row.payState | formatPayState }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.payState === 1 && scope.row.userType === 1" v-permission="['POST /admin/activity/activityGroupon/changeUserType']" type="primary" size="mini" @click="handleChangeNew(scope.row)">转新学员</el-button>
          <el-button v-if="scope.row.payState === 1 && scope.row.userType === 2" v-permission="['POST /admin/activity/activityGroupon/changeUserType']" type="primary" size="mini" @click="handleChangeOld(scope.row)">转老学员</el-button>
          <el-button v-if="scope.row.payState === 1 && scope.row.grouponId === 0 && scope.row.subVoList.length > 1" v-permission="['POST /admin/activity/activityGroupon/replaceCaptain']" type="danger" size="mini" @click="handleReplaceCaptain(scope.row)">换团长</el-button>
          <el-button v-if="scope.row.payState === 1 && (scope.row.grouponId !== 0 || (scope.row.grouponId === 0 && scope.row.subVoList.length === 1))" v-permission="['POST /admin/activity/activityGroupon/changeGroupon']" type="danger" size="mini" @click="handleChangeGroupon(scope.row)">调去其他团</el-button>
          <el-button v-if="scope.row.payState === 1 && scope.row.grouponId !== 0" v-permission="['POST /admin/activity/activityGroupon/independent']" type="primary" size="mini" @click="handleIndependent(scope.row)">独立成团</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 更换团长对话框 -->
    <el-dialog :visible.sync="replaceDialogVisible" title="更换团长">
      <el-form ref="grouponForm" :model="grouponForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="请选本团团员" prop="userId">
          <el-select v-model="grouponForm.userName" placeholder="请选择" @change="changeCaptain(grouponForm)">
            <el-option v-for="item in grouponUser" :key="item.userId" :label="item.userName" :value="item.userId" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeReplace()">取消</el-button>
        <el-button type="primary" @click="confirmReplace">确定</el-button>
      </div>
    </el-dialog>

    <!-- 换团对话框 -->
    <el-dialog :visible.sync="changeGrouponDialogVisible" title="换团">
      <el-form ref="activityGrouponForm" :model="activityGrouponForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="请选本活动的其他团" prop="grouponCode">
          <el-select v-model="activityGrouponForm.desc" placeholder="请选择" @change="changeGroup(activityGrouponForm)">
            <el-option v-for="item in activityGroupons" :key="item.grouponCode" :label="item.desc" :value="item.grouponCode" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeChange()">取消</el-button>
        <el-button type="primary" @click="confirmChangeGroupon">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { activityDetail, activityGrouponList, exportGrouponList, changeUserType, listGrouponUser, replaceCaptain, listActivityGroupon, changeGroupon, independent } from '@/api/activitylist'
import { statGrouponsByActivityId, statStatisticsByActivityId, statOrderByActivityId } from '@/api/stat'
import VeHistogram from 'v-charts/lib/histogram'
import VeLine from 'v-charts/lib/line'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

const defaultTypeOptions = [
  {
    label: '团购',
    value: 1
  }
]

const defaultGrouponStateOptions = [
  {
    label: '待确认',
    value: 0
  },
  {
    label: '成功',
    value: 1
  },
  {
    label: '失败',
    value: 2
  }
]

const defaultPayStateOptions = [
  {
    label: '未支付',
    value: 0
  },
  {
    label: '支付成功',
    value: 1
  },
  {
    label: '支付失败',
    value: 2
  }
]

const defaultUserTypeOptions = [
  {
    label: '老学员',
    value: 1
  },
  {
    label: '新学员',
    value: 2
  }
]

export default {
  name: 'ActivityGrouponDetail',
  components: { VeHistogram, VeLine, Pagination },
  filters: {
    formatType(type) {
      for (let i = 0; i < defaultTypeOptions.length; i++) {
        if (type === defaultTypeOptions[i].value) {
          return defaultTypeOptions[i].label
        }
      }
      return ''
    },
    formatState(state) {
      if (state === 0) {
        return '待发布'
      } else if (state === 1) {
        return '发布中'
      } else if (state === 2) {
        return '到期自动下线'
      } else if (state === 3) {
        return '手动下线'
      } else {
        return '未知'
      }
    },
    formatGrouponId(grouponId) {
      if (grouponId === 0) {
        return '团长'
      } else {
        return '团员'
      }
    },
    formatUserType(userType) {
      if (userType === 1) {
        return '老学员'
      } else {
        return '新学员'
      }
    },
    formatGrouponState(state) {
      if (state === 0) {
        return '待确认'
      } else if (state === 1) {
        return '成功'
      } else {
        return '失败'
      }
    },
    formatPayState(payState) {
      if (payState === 0) {
        return '未支付'
      } else if (payState === 1) {
        return '支付成功'
      } else {
        return '支付失败'
      }
    }
  },
  data() {
    return {
      typeOptions: Object.assign({}, defaultTypeOptions),
      stateOptions: Object.assign({}, defaultGrouponStateOptions),
      payStateOptions: Object.assign({}, defaultPayStateOptions),
      userTypeOptions: Object.assign({}, defaultUserTypeOptions),
      chartData: {},
      chartSettings: {},
      chartExtend: {},
      activity: {},
      list: [],
      exportList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        activityId: null,
        grouponCode: '',
        userType: null,
        subject: '',
        userName: '',
        state: null,
        sort: 'groupon_code',
        order: 'desc'
      },
      grouponForm: {
        id: undefined,
        userId: undefined,
        userName: undefined
      },
      activityGrouponForm: {
        id: undefined,
        grouponCode: undefined,
        desc: undefined
      },
      replaceDialogVisible: false,
      changeGrouponDialogVisible: false,
      downloadLoading: false,
      grouponUser: [],
      activityGroupons: []
    }
  },
  created() {
    this.init()
    statGrouponsByActivityId(this.$route.query.id).then(response => {
      this.grouponDatas = response.data.data
      this.chartSettings = {
        labelMap: {
          'total': '开团、参团总数量',
          'captains': '开团数量',
          'members': '参团数量'
        }
      }
      this.chartExtend = {
        xAxis: { boundaryGap: true },
        series: {
          label: { show: true, position: 'top' },
          barMaxWidth: 35
        },
        dataZoom: [
          {
            type: 'inside'
          }
        ]
      }
    })

    statStatisticsByActivityId(this.$route.query.id).then(response => {
      this.statisticsDatas = response.data.data
      this.statisticsSettings = {
        labelMap: {
          'views': '浏览数',
          'applications': '分享数',
          'shares': '报名数',
          'groupons': '成团数'
        }
      }
      this.chartExtend = {
        xAxis: { boundaryGap: true },
        series: {
          label: { show: true, position: 'top' },
          barMaxWidth: 35
        },
        dataZoom: [
          {
            type: 'inside'
          }
        ]
      }
    })

    statOrderByActivityId(this.$route.query.id).then(response => {
      this.orderDatas = response.data.data
      this.orderSettings = {
        labelMap: {
          'orders': '总订单',
          'vailds': '有效订单',
          'invailds': '无效订单',
          'amount': '收款金额',
          'refundAmount': '退款金额'
        }
      }
      this.chartExtend = {
        xAxis: { boundaryGap: true },
        series: {
          label: { show: true, position: 'top' },
          barMaxWidth: 35
        },
        dataZoom: [
          {
            type: 'inside'
          }
        ]
      }
    })
  },
  methods: {
    init: function() {
      if (this.$route.query.id == null) {
        return
      }
      activityDetail(this.$route.query.id).then(response => {
        this.activity = response.data.data
      })
      this.listQuery.activityId = this.$route.query.id
      this.getList()
      this.getExportList()
    },
    getList() {
      this.listLoading = true
      activityGrouponList(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    getExportList() {
      exportGrouponList(this.listQuery)
        .then(response => {
          this.exportList = response.data.data.list
        })
        .catch(() => {
          this.exportList = []
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
      this.getExportList()
    },
    closeReplace() {
      this.replaceDialogVisible = false
      this.grouponForm.userName = ''
    },
    changeCaptain(item) {
      this.grouponForm.userId = item.userName
      this.grouponForm.userName = item.userName
    },
    closeChange() {
      this.changeGrouponDialogVisible = false
      this.activityGrouponForm.grouponCode = ''
      this.activityGrouponForm.desc = ''
    },
    changeGroup(item) {
      this.activityGrouponForm.grouponCode = item.desc
    },
    handleChangeNew(row) {
      changeUserType({ id: row.id, userType: 2 }).then(response => {
        this.$notify.success({
          title: '成功',
          message: '成功转为新学员'
        })
        this.getList()
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })
    },
    handleChangeOld(row) {
      changeUserType({ id: row.id, userType: 1 }).then(response => {
        this.$notify.success({
          title: '成功',
          message: '成功转为老学员'
        })
        this.getList()
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })
    },
    handleIndependent(row) {
      independent({ id: row.id }).then(response => {
        this.$notify.success({
          title: '成功',
          message: '成功成团'
        })
        this.getList()
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })
    },
    handleReplaceCaptain(row) {
      listGrouponUser({ grouponCode: row.grouponCode }).then(response => {
        this.grouponUser = response.data.data
      })

      this.grouponForm.id = row.id
      this.grouponForm.userId = row.userId

      this.replaceDialogVisible = true
      this.$nextTick(() => {
        this.$refs['grouponForm'].clearValidate()
      })
    },
    confirmReplace() {
      this.$refs['grouponForm'].validate((valid) => {
        if (valid) {
          replaceCaptain(this.grouponForm).then(response => {
            this.replaceDialogVisible = false

            this.$notify.success({
              title: '成功',
              message: '更换团长成功'
            })
            this.grouponForm.userName = ''
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },
    handleChangeGroupon(row) {
      listActivityGroupon({ id: row.id }).then(response => {
        this.activityGroupons = response.data.data
      })

      this.activityGrouponForm.id = row.id
      this.activityGrouponForm.grouponCode = row.grouponCode

      this.changeGrouponDialogVisible = true
      this.$nextTick(() => {
        this.$refs['activityGrouponForm'].clearValidate()
      })
    },
    confirmChangeGroupon() {
      this.$refs['activityGrouponForm'].validate((valid) => {
        if (valid) {
          changeGroupon(this.activityGrouponForm).then(response => {
            this.changeGrouponDialogVisible = false

            this.$notify.success({
              title: '成功',
              message: '更换团成功'
            })
            this.activityGrouponForm.grouponCode = ''
            this.activityGrouponForm.desc = ''
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '团编号',
          '团人数/满人',
          '微信名',
          '学员姓名',
          '学员年龄',
          '联系电话',
          '科目',
          '学员类型',
          '是否团长',
          '开团/参团状态',
          '订单号',
          '微信支付单号',
          '支付金额(元)',
          '支付状态'
        ]
        const filterVal = [
          'grouponCode',
          'grouponSize',
          'userName',
          'contactName',
          'userAge',
          'contactPhone',
          'subject',
          'userType',
          'grouponId',
          'state',
          'orderCode',
          'payId',
          'orderPrice',
          'payState'
        ]
        const list = this.exportList
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel3(
          tHeader,
          data,
          '团购详细信息'
        )
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'userType') {
          if (v[j] === 1) {
            return '老学员'
          } else {
            return '新学员'
          }
        } else if (j === 'grouponId') {
          if (v[j] === 0) {
            return '团长'
          } else {
            return '团员'
          }
        } else if (j === 'state') {
          if (v[j] === 0) {
            return '待确认'
          } else if (v[j] === 1) {
            return '成功'
          } else {
            return '失败'
          }
        } else if (j === 'payState') {
          if (v[j] === 0) {
            return '未支付'
          } else if (v[j] === 1) {
            return '支付成功'
          } else {
            return '支付失败'
          }
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style scoped>
  .filter-container {
    margin-top: 20px;
  }

  .table-layout {
    margin-top: 20px;
    border-left: 1px solid #DCDFE6;
    border-top: 1px solid #DCDFE6;
  }

  .table-cell {
    height: 60px;
    line-height: 40px;
    border-right: 1px solid #DCDFE6;
    border-bottom: 1px solid #DCDFE6;
    padding: 10px;
    font-size: 14px;
    color: #606266;
    text-align: center;
    overflow: hidden;
  }
  .table-cell-title {
    border-right: 1px solid #DCDFE6;
    border-bottom: 1px solid #DCDFE6;
    padding: 10px;
    background: #F2F6FC;
    text-align: center;
    font-size: 14px;
    color: #303133;
  }
  .groupon-list {
    display: flex;
    justify-content: space-around;
    justify-items: center;
    align-items: center;
    padding: 6px 0;
  }

  .groupon-cell {
    height: 38px;
    line-height: 38px;
    padding: 0px;
    font-size: 14px;
    color: #606266;
    text-align: center;
    overflow: hidden;
  }

</style>
